package com.interactive1.dbutils;
import java.util.*;

public class Search  {
	private String alias;
	private String pattern;
	private boolean ignoreCase;
	private int _progress;
	private int _done;
	private int _total;
	
 	public Search(String alias, String pattern) {
		this(alias, pattern, false);
	}

	public Search(String alias, String pattern, boolean ignoreCase) {
		this.alias = alias;
		this.pattern = pattern;
		this.ignoreCase = ignoreCase;
	}

	public Map search() throws Exception {
		Hashtable res = new Hashtable();
		String query = "SELECT TABLE_NAME FROM USER_TABLES";
		Result tables = DBUtil.select(alias, query);
		_total = tables.noRows;

		while (tables.next()) {
			String table = tables.getString(0);
			Result rows = search(table, true);
			if (rows!=null && rows.noRows>0) {
				res.put(table, rows);
			}
			_progress = (int)(++_done*100f/_total+0.5);
		}
		return res;
	}
	
	public Map search(String table) throws Exception {
		Hashtable res = new Hashtable();
		Result rows = search(table, true);
		if (rows!=null && rows.noRows>0) {
			res.put(table, rows);	
		}
		_progress = 100;
		return res;
	}
	
	public int progress() {
		return _progress;
	}
	
	private Result search(String table, boolean internal) {
		Result res = null;
		if (internal);
		try {
			String query = "SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE UPPER(TABLE_NAME)=UPPER('"+table+"')";
			Result cols = DBUtil.select(alias, query);
			String q = "";
			while (cols.next()) {
				if (!q.equals(""))  {
					q+= " OR ";
				}
				if (ignoreCase)  {
					q += "LOWER("+cols.getString(0)+") LIKE '"+pattern.toLowerCase()+"'";
				} else  {
					q += cols.getString(0)+" LIKE '"+pattern+"'";
				}
			}
			query = "SELECT * FROM "+table+" WHERE "+q;
			res = DBUtil.select(alias, query);
		} catch (Exception e) {
		}
		return res;
	}
}